package com.sogeti.mentormatch.aop.spring;

import com.sogeti.mentormatch.aop.QueryFinderExecutor;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.IntroductionInterceptor;

/**
 * @author Matthew L. Maurer <maurer.it@gmail.com>
 */
public class QueryFinderIntroductionInterceptor implements
    IntroductionInterceptor
{
    @SuppressWarnings("unchecked")
    public Object invoke ( MethodInvocation methodInvocation ) throws Throwable
    {

        QueryFinderExecutor executor = ( QueryFinderExecutor ) methodInvocation
                .getThis();

        String methodName = methodInvocation.getMethod().getName();
        if ( methodName.startsWith("find") || methodName.startsWith("list") ) {
            Object[ ] arguments = methodInvocation.getArguments();
            return executor.executeQueryFinder(methodInvocation.getMethod(),
                    arguments);
        }
        else if ( methodName.startsWith("iterate") ) {
            Object[ ] arguments = methodInvocation.getArguments();
            return executor.iterateQueryFinder(methodInvocation.getMethod(),
                    arguments);
        }
        else {
            return methodInvocation.proceed();
        }
    }

    @SuppressWarnings ( "unchecked" )
    public boolean implementsInterface ( Class intf ) {
        return intf.isInterface()
                && QueryFinderExecutor.class.isAssignableFrom(intf);
    }
}
